//
//  JKEmojiKeyboardViewController.swift
//  表情键盘
//
//  Created by albert on 16/6/26.
//  Copyright © 2016年 albert. All rights reserved.
//  表情键盘控制器

import UIKit

class JKEmojiKeyboardViewController: UIViewController {
    
    /** 保存所有组表情数据 */
    var packages: [JKEmojiKeyboardPackage] = JKEmojiKeyboardPackage.loadEmojiPachages()
    
    /** 选中的表情组按钮 */
    var selectedButton: UIButton?
    
    /** 闭包回调传值 */
    var emoticonCallBack: (emoticon: JKEmojiModel) -> ()
    
    init(callBack: (emoticon: JKEmojiModel) -> ()) {
        self.emoticonCallBack = callBack
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = JKGlobalBackGroundColor
        
        // 1.添加子控件
        view.addSubview(collectionView)
        view.addSubview(toolBarView)
        
        // 2.布局子控件
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        toolBarView.translatesAutoresizingMaskIntoConstraints = false
        
        let dict = ["collectionView" : collectionView, "toolBarView" : toolBarView]
        var cons = NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[collectionView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict)
        cons += NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[toolBarView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict)
        cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[collectionView]-[toolBarView(49)]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict)
        view.addConstraints(cons)
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        // 表情键盘出来的时候默认显示默认表情
        let indexPath = NSIndexPath(forItem: 0, inSection: 1)
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
        
        let btn = toolBarView.subviews[indexPath.section] as! UIButton
        btn.selected = true
        selectedButton = btn
    }
    
    /** 点击底部工具条按钮 */
    @objc private func itemClick(item: UIButton) {
        
        selectedButton?.selected = false
        item.selected = true
        selectedButton = item
        
        let indexPath = NSIndexPath(forItem: 0, inSection: item.tag)
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
    }
    
    // MARK: - 懒加载
    /** collectionView */
    private lazy var collectionView: UICollectionView = {
        let clv = UICollectionView(frame: CGRectZero, collectionViewLayout: JKEmojiKeyboardFlowLayout())
        
        clv.backgroundColor = JKGlobalBackGroundColor
        clv.dataSource = self
        clv.delegate = self
        clv.registerClass(JKEmojiKeyboardCell.self, forCellWithReuseIdentifier: "keyboardCell")
        
        return clv
    }()
    
    /** 底部按钮工具条 */
    private lazy var toolBarView: UIView = {
        let tbv = UIView()
        
        // 设置工具条背景及尺寸
        tbv.backgroundColor = UIColor(red: 249.0/255.0, green: 249.0/255.0, blue: 249.0/255.0, alpha: 1)
        tbv.bounds = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 49)
        
        var index = 0
        let titles = ["最近", "默认", "Emoji", "浪小花"]
        for title in titles {
            
            // 创建按钮
            let btn = UIButton(type: UIButtonType.Custom)
            tbv.addSubview(btn)
            
            // 设置frame
            let width = tbv.bounds.width / CGFloat(titles.count)
            let height = tbv.bounds.height
            let x = CGFloat(index) * width
            let y: CGFloat = 0
            btn.frame = CGRect(x: x, y: y, width: width, height: height)
            
            // 设置文字、字体颜色及选中状态背景图片
            btn.setTitle(title, forState: UIControlState.Normal)
            btn.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
            btn.setBackgroundImage(UIImage(named: "emojiMenuBg"), forState: UIControlState.Selected)
            
            // 添加事件
            btn.addTarget(self, action: "itemClick:", forControlEvents: UIControlEvents.TouchUpInside)
            // 绑定tag
            btn.tag = index++
        }
        
        return tbv
    }()
}

// MARK: - 数据源
extension JKEmojiKeyboardViewController: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return packages.count
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return packages[section].emoticons?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("keyboardCell", forIndexPath: indexPath) as! JKEmojiKeyboardCell
        
        let emojiIcon = packages[indexPath.section].emoticons![indexPath.item]
        
        cell.emojiIcon = emojiIcon
        
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        // 1.监听表情点击
        let package = packages[indexPath.section]
        let emoticon = package.emoticons![indexPath.item]
        
        // 2.记录点击的表情，并放入最近中
        // 每使用一次就+1
        emoticon.useCount++
        
        // 判断是否是删除按钮
        if !emoticon.isDeleteButton {
            // 将当前点击的表情添加到最近组中
            packages[0].addLatestEmoji(emoticon)
            collectionView.reloadData()
        }
        
        // 3.将表情传递给外面的控制器
        emoticonCallBack(emoticon: emoticon)
    }
    
    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        
        // 获取当前可见cell第一个的索引
        let cell = collectionView.visibleCells().first!
        let indexPath = collectionView.indexPathForCell(cell)!
        
        // 设置选中状态
        if selectedButton?.tag != indexPath.section {
            let btn = toolBarView.subviews[indexPath.section] as! UIButton
            btn.selected = true
            selectedButton?.selected = false
            selectedButton = btn
        }
    }
}

// MARK: - 自定义流水布局
class JKEmojiKeyboardFlowLayout: UICollectionViewFlowLayout {
    override func prepareLayout() {
        super.prepareLayout()
        
        // 1.计算cell宽度
        let width = UIScreen.mainScreen().bounds.size.width / 7
        let height = collectionView!.frame.height / 3
        itemSize = CGSize(width: width, height: height)
        minimumInteritemSpacing = 0
        minimumLineSpacing = 0
        scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        // 2.设置collectionView
        collectionView?.bounces = false
        collectionView?.pagingEnabled = true
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.showsVerticalScrollIndicator = false
        
        // 还是直接算cell高度吧，这样还是有bug，比如collectionView的高度不足以显示三行
        // 3.设置间隙，如果不处理的话，系统会默认把间隙添加到cell之间，这里将间隙调整到上下位置，保证cell之间没有间隙
        // 注意：在iPhone4/4s上如果写为0.5会有bug
        //let offsetY = (collectionView!.frame.height - 3 * width) * 0.4999
        //collectionView?.contentInset = UIEdgeInsets(top: offsetY, left: 0, bottom: offsetY, right: 0)
    }
}
